package xyz.bernkastel.goods_in_great_demand.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import xyz.bernkastel.goods_in_great_demand.common.BaseContext;
import xyz.bernkastel.goods_in_great_demand.common.R;
import xyz.bernkastel.goods_in_great_demand.dto.OrdersDto;
import xyz.bernkastel.goods_in_great_demand.entity.*;
import xyz.bernkastel.goods_in_great_demand.service.*;

import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/order")
public class OrderController {
    @Autowired
    private OrderService orderService;
    @Autowired
    private UserService userService;
    @Autowired
    private AddressBookService addressBookService;
    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private ShoppingCartService shoppingCartService;

    /**
     * 用户下单
     *
     * @param orders
     * @return
     */
    @PostMapping("/submit")
    public R<String> submit(@RequestBody OrdersDto orders) {
        log.info("订单数据:{}", orders);
        orderService.submit(orders);
        return R.success("下单成功");
    }

    /**
     * 订单信息分页
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping({"/page"})
    public R<Page> page(int page, int pageSize, String name) {
        Page<Orders> pageInfo = new Page<>(page, pageSize);
        Page<OrdersDto> ordersDtoPage = new Page<>();
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();

        //过滤条件
        queryWrapper.like(name != null, Orders::getUserName, name);
        queryWrapper.orderByDesc(Orders::getOrderTime);

        //执行分页查询
        orderService.page(pageInfo, queryWrapper);

        BeanUtils.copyProperties(pageInfo, ordersDtoPage, "records");
        List<Orders> records = pageInfo.getRecords();
        List<OrdersDto> list = records.stream().map((item) -> {
            //拷贝数据
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(item, ordersDto);
            //id
            Long userId = item.getUserId();
            //根据分类id查找对象
            User user = userService.getById(userId);
            if (user != null) {
                //用户名名称
                //地址
                Long addressBookId = item.getAddressBookId();
                AddressBook addressBook = addressBookService.getById(addressBookId);
                if (addressBook != null) {
                    String userName = addressBook.getConsignee();
                    ordersDto.setUserName(userName);
                    // String address = addressBook.getProvinceName()+"-"+addressBook.getCityName()+"-"+addressBook.getDistrictName()+"-"+addressBook.getDetail();
                    String address = addressBook.getDetail();
                    ordersDto.setAddress(address);
                }
            }
            LambdaQueryWrapper<OrderDetail> queryWrapper1 = new LambdaQueryWrapper();
            queryWrapper1.eq(OrderDetail::getOrderId, item.getId());
            List<OrderDetail> orderDetails = orderDetailService.list(queryWrapper1);
            ordersDto.setOrderDetails(orderDetails);

            return ordersDto;
        }).collect(Collectors.toList());
        ordersDtoPage.setRecords(list);
        return R.success(ordersDtoPage);
    }

    /**
     * 用户订单分页查询
     *
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/userPage")
    public R<Page> page(int page, int pageSize) {
        //分页构造器对象
        Page<Orders> pageInfo = new Page<>(page, pageSize);
        Page<OrdersDto> pageDto = new Page<>(page, pageSize);
        //构造条件查询对象
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Orders::getUserId, BaseContext.getCurrentId());
        //这里是直接把当前用户分页的全部结果查询出来，要添加用户id作为查询条件，否则会出现用户可以查询到其他用户的订单情况
        //添加排序条件，根据更新时间降序排列
        queryWrapper.orderByDesc(Orders::getOrderTime);
        orderService.page(pageInfo, queryWrapper);

        //通过OrderId查询对应的OrderDetail
        LambdaQueryWrapper<OrderDetail> queryWrapper2 = new LambdaQueryWrapper<>();

        //对OrderDto进行需要的属性赋值
        List<Orders> records = pageInfo.getRecords();
        List<OrdersDto> ordersDtoList = records.stream().map((item) -> {
            OrdersDto ordersDto = new OrdersDto();
            //此时的orderDto对象里面orderDetails属性还是空 下面准备为它赋值
            Long orderId = item.getId();//获取订单id
            List<OrderDetail> orderDetailList = this.getOrderDetailListByOrderId(orderId);

            BeanUtils.copyProperties(item, ordersDto);
            //对orderDto进行OrderDetails属性的赋值
            ordersDto.setOrderDetails(orderDetailList);
//            ordersDto.setUserName(item.getUserName());
//            ordersDto.setAddress(item.getAddress());
//            ordersDto.setConsignee(item.getConsignee());
//            ordersDto.setPhone(item.getPhone());
            return ordersDto;
        }).collect(Collectors.toList());

        //使用dto的分页有点难度.....需要重点掌握
        BeanUtils.copyProperties(pageInfo, pageDto, "records");
        pageDto.setRecords(ordersDtoList);
        return R.success(pageDto);
    }

    public List<OrderDetail> getOrderDetailListByOrderId(Long orderId) {
        LambdaQueryWrapper<OrderDetail> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OrderDetail::getOrderId, orderId);
        List<OrderDetail> orderDetailList = orderDetailService.list(queryWrapper);
        return orderDetailList;
    }


    @PutMapping
    public R<String> update(@RequestBody Orders orders) {
        log.info(orders.toString());

        orderService.updateById(orders);
        return R.success("更新用户信息成功");
    }

    /**
     * 再来一单
     *
     * @return
     */
    @Transactional
    @PostMapping("/again")
    public R<String> again(@RequestBody Orders orders, HttpServletResponse resp) {
        //根据订单号从order_detail中查出订单详细信息
        List<OrderDetail> orderDetailList = getOrderDetailListByOrderId(orders.getId());
        //先清空购物车
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId, BaseContext.getCurrentId());
        shoppingCartService.remove(queryWrapper);
        //将订单详细信息中的商品转存到购物车中
        for (int i = 0; i < orderDetailList.size(); i++) {
            ShoppingCart shoppingCart = new ShoppingCart();
            shoppingCart.setId(orderDetailList.get(i).getId());
            shoppingCart.setName(orderDetailList.get(i).getName());
            shoppingCart.setUserId(BaseContext.getCurrentId());
            shoppingCart.setGoodsId(orderDetailList.get(i).getGoodsId());
            shoppingCart.setSetmealId(orderDetailList.get(i).getSetmealId());
            shoppingCart.setGoodsTag(orderDetailList.get(i).getGoodsTag());
            shoppingCart.setNumber(orderDetailList.get(i).getNumber());
            shoppingCart.setAmount(orderDetailList.get(i).getAmount());
            shoppingCart.setImage(orderDetailList.get(i).getImage());
            shoppingCart.setCreateTime(LocalDateTime.now());

            shoppingCartService.save(shoppingCart);
        }
        return R.success("已添加商品到购物车");
    }
}
